﻿/*
 * ======================================================================
 *                           Modern Warfare3 Launcher
 * Copyright 2011-2012
 * Developer:Pooya parsa
 * Email:pingsft@gmail.com
 * You are ALLOWED:
 * -Read source code
 * -Use some part of source code with Full name and email of developer
 * -Release your own mod with name of develepor
 * You are NOT ALLOWD:
 * -Add cracked version of Mw3
 * -Release modified version as MW3Launcher
 * -Mirror Sourcecode
 * -Use source code without name of developer
 * Thank you for your attention
 * ======================================================================
 * */
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using MW3Launcher;
namespace MW3Launcher
{
    public partial class MainWindow : Form
    {
        private const int ACLOC = 0x1f0fff;
        private glass_helper AeroGlass;
        private window_mover Mover;
        Config _Config;
        public MainWindow()
        {
            InitializeComponent();
            InitializeEvents();
            AeroGlass = new glass_helper(this);
            Mover = new window_mover(this);
            _Config = new Config();
        }

        public void InitializeEvents()
        {
            btnMPLAN.Click += new EventHandler(btnMPLAN_Click);
            btnMPDC.Click += new EventHandler(btnMPDC_Click);
            btnMPDedi.Click += new EventHandler(btnMPDedi_Click);
            btnProfileDumper.Click += new EventHandler(btnProfileDumper_Click);
            btnSPH.Click += new EventHandler(btnSPH_Click);
            btnSettings.Click += new EventHandler(btnSettings_Click);
            checkBox1.CheckedChanged += new EventHandler(checkBox1_CheckedChanged);
            IpBox.LostFocus += new EventHandler(IpBox_LostFocus);
            PortBox.LostFocus += new EventHandler(PortBox_LostFocus);
            BtnSpc.Click += new EventHandler(BtnSpc_Click);
            this.Load += new EventHandler(MainWindow_Load);

        }
      
        //Events
        public void MainWindow_Load(object sender, EventArgs e)
        {
            AeroGlass.applyAeroGlass(0, 0,0, 25);
            Mover.make_movable_all();
            Mover.make_movable(lblStatus);
            Mover.make_movable(tabHome);
            string CurrentVer = "";
            if (File.Exists("MW3Launcher.inf")) CurrentVer = File.ReadAllText("MW3Launcher.inf");
            if (CurrentVer == "")
            {
                if (MessageBox.Show("It seems you just installed MW3launcher.\nClick yes to start update", "Update", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    StartUpdate();
            }
            else
            {
                if (_Config.Offline != "1") 
                new Thread(new ThreadStart(CheckNewVersion)).Start();
            }


          //
        s:
            for (int i = 0; i < _Config.NeededFiles.Length; i++)
            {
                string FileName = _Config.NeededFiles[i];
                if (!System.IO.File.Exists(FileName))
                    if (MessageBox.Show("Cannot find file '" + FileName + "'\nStart update?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) != System.Windows.Forms.DialogResult.Yes)
                        Environment.Exit(0);
                    else
                    {
                        StartUpdate();
                        goto s;
                    }
            }

            if (!System.IO.File.Exists(@".\devraw\video\startup.bik"))
            {
                if (!Directory.Exists(@".\devraw\video"))
                {
                    Directory.CreateDirectory(@".\devraw\video");
                }
                string path = @".\devraw\video\startup.bik";
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
                byte[] input = Properties.Resources.MW3Launchertekntup;
                FileStream output = System.IO.File.Open(path, FileMode.CreateNew);
                output.Write(input, 0, input.Length);
                output.Dispose();
            }
            if (!System.IO.File.Exists("teknogods.ini"))
            {
                MessageBox.Show("It seems that this is your first time running our loader, you must first set your nickname.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                new Settings().ShowDialog();
            }
            else
            {
                try
                {
                    if (System.IO.File.Exists("teknogods.ini"))
                    {

                        IniParser parser = new IniParser("teknogods.ini");
                        string setting = parser.GetSetting("Settings", "Name");
                        if (parser.GetSetting("Settings", "ID") == "/")
                        {
                            System.IO.File.Delete("teknogods.ini");
                            MessageBox.Show("It seems that you have malformed SteamID because of bug in 1.2 version, you are required to refill info.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            new Settings().ShowDialog();
                        }
                        if (string.IsNullOrEmpty(setting))
                        {
                            System.IO.File.Delete("teknogods.ini");
                            MessageBox.Show("It seems that this is your first time running our loader, you must first set your nickname.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            new Settings().ShowDialog();
                        }
                    }
                }
                catch (Exception)
                {
                    System.IO.File.Delete("teknogods.ini");
                    
                    new Settings().ShowDialog();
                }
            }
            this.PortBox.Text = "27016";

            if (string.IsNullOrEmpty(this.IpBox.Text))
            {
                this.IpBox.Text = "127.0.0.1";
            }
            if (File.Exists("teknogods.ini"))
            {
                IniParser parser = new IniParser("teknogods.ini");
                lblStatus.lblText= "Logged in as: "+parser.GetSetting("Settings", "Name");

            }
        if(_Config.Offline!="1")
            new Thread(new ThreadStart(FetchNews)).Start();

        }


        public void BtnSpc_Click(object sender, EventArgs e)
        {
            if ((this.IpBox.Text == "Invalid host."))// || string.IsNullOrWhiteSpace(this.IpBox.Text))
            {
                MessageBox.Show("Please enter correct IP before you continue as a client!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else if (!System.IO.File.Exists("iw5sp.exe"))
            {
                MessageBox.Show("Cannot find iw5sp.exe");
            }
            else if (!this.IsAssemblySigned("iw5sp.exe"))
            {
                MessageBox.Show("Modern Warfare 3 SP Assembly signature is not valid, please reinstall your game!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                base.Close();
            }
            else
            {
                string ip = this.GetIp(this.IpBox.Text);
                if (ip != string.Empty)
                {
                    this.StartTheProcess("iw5sp.exe", "+server " + ip + ":0");
                }
            }
        }

        void btnSettings_Click(object sender, EventArgs e)
        {
            new Settings().ShowDialog();
        }

        public void btnSPH_Click(object sender, EventArgs e)
        {
            if (!System.IO.File.Exists("iw5sp.exe"))
            {
                MessageBox.Show("Cannot find iw5sp.exe");
            }
            else if (!this.IsAssemblySigned("iw5sp.exe"))
            {
                MessageBox.Show("Modern Warfare 3 SP Assembly signature is not valid, please reinstall your game!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                base.Close();
            }
            else
            {
                this.StartTheProcess("iw5sp.exe", string.Empty);
            }
        }

        void btnProfileDumper_Click(object sender, EventArgs e)
        {
            byte[] bytes = Encoding.ASCII.GetBytes("teknomw3.dll");
            if (MessageBox.Show("This is only intented if you have the game running in the backround connected to Steam and it is recommented that you are in the barracks.", "Are you sure you want to continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No)
            {
                Process[] processArray = getProcesses("iw5mp.exe");
                if (processArray == null)
                {
                    MessageBox.Show("Target process not found");
                }
                else
                {
                    IntPtr hProcess = Win32Apis.OpenProcess(0x1f0fff, false, processArray[0].Id);
                    if (hProcess == IntPtr.Zero)
                    {
                        MessageBox.Show("Target process pointer is invalid");
                    }
                    else
                    {
                        IntPtr procAddress = (IntPtr)((uint)Win32Apis.GetProcAddress(Win32Apis.GetModuleHandle("Kernel32.dll"), "LoadLibraryA"));
                        if (procAddress == IntPtr.Zero)
                        {
                            MessageBox.Show("Loadlibrary unreachable");
                        }
                        else
                        {
                            int num = bytes.Length + 1;
                            IntPtr lpBaseAddress = Win32Apis.VirtualAllocEx(hProcess, new IntPtr(0), (uint)num, Win32Apis.AllocationType.COMMIT, Win32Apis.MemoryProtection.READWRITE);
                            if (lpBaseAddress == IntPtr.Zero)
                            {
                                MessageBox.Show("Virtual alloc failure");
                            }
                            else
                            {
                                UIntPtr ptr4;
                                Win32Apis.WriteProcessMemory(hProcess, lpBaseAddress, bytes, (uint)num, out ptr4);
                                if (ptr4 == ((UIntPtr)0))
                                {
                                    MessageBox.Show("Write process mem failure");
                                }
                                else
                                {
                                    int num2 = processArray[0].Id ^ 0x80;
                                    Mutex mutex = new Mutex(false, "TeknoPDump" + num2.ToString("X8"));
                                    Win32Apis.CreateRemoteThread(hProcess, new IntPtr(0), new IntPtr(0), procAddress, lpBaseAddress, 0, IntPtr.Zero);
                                    Win32Apis.CloseHandle(hProcess);
                                    Thread.Sleep(0x1770);
                                    mutex.Close();
                                }
                            }
                        }
                    }
                }
            }
        }
        public void btnMPLAN_Click()
        {
            btnMPLAN_Click(null, null);
        }
        public void btnMPLAN_Click(object sender, EventArgs e)
        {
            if (!System.IO.File.Exists("iw5mp.exe"))
            {
                MessageBox.Show("Cannot find iw5mp.exe\nAre you sure that program is in MW3 game folder?");
            }
            else if (!this.IsAssemblySigned("iw5mp.exe"))
            {
                MessageBox.Show("Modern Warfare 3 MP Assembly signature is not valid, please reinstall your game!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                base.Close();
            }
            else
            {
                this.StartTheProcess("iw5mp.exe", (this.checkBox1.Checked == true) ? "+usekeys" : string.Empty);
            }
        }

        void btnMPDedi_Click(object sender, EventArgs e)
        {
            if (!System.IO.File.Exists("MW3LauncherDedicated_ServerStarter.exe"))
            {
                MessageBox.Show("Cannot find MW3LauncherDedicated_ServerStarter.exe");
            }
            else
            {
                this.StartTheProcess("MW3LauncherDedicated_ServerStarter.exe", "+set dedicated 1 +set net_port " + this.PortBox.Text);
            }
        }

        void btnMPDC_Click(object sender, EventArgs e)
        {
            if ((this.IpBox.Text == "Invalid host."))// || string.IsNullOrWhiteSpace(this.IpBox.Text))
            {
                MessageBox.Show("Please enter correct IP before you continue as a client!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else if (!System.IO.File.Exists("iw5mp.exe"))
            {
                MessageBox.Show("Cannot find iw5mp.exe");
            }
            else if (!this.IsAssemblySigned("iw5mp.exe"))
            {
                MessageBox.Show("Modern Warfare 3 MP Assembly signature is not valid, please reinstall your game!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                base.Close();
            }
            else
            {
                string ip = this.GetIp(this.IpBox.Text);
                if (ip != string.Empty)
                {
                    this.StartTheProcess("iw5mp.exe", "+server " + ip + ":" + this.PortBox.Text);
                }
            }
        }

        void PortBox_LostFocus(object sender, EventArgs e)
        {
            try
            {
                TextBox box = (TextBox)sender;
                int num = Convert.ToInt32(box.Text);
                if (num >= 0xffff)
                {
                    this.PortBox.Text = "27016";
                }
                else
                {
                    box.Text = num.ToString();
                }
            }
            catch (Exception)
            {
                this.PortBox.Text = "27016";
            }
        }

        void IpBox_LostFocus(object sender, EventArgs e)
        {

            try
            {
                TextBox box = (TextBox)sender;
                UriHostNameType type = Uri.CheckHostName(box.Text);
                switch (type)
                {
                    case UriHostNameType.Unknown:
                    case UriHostNameType.Basic:
                        box.Text = "Invalid host.";
                        return;
                }
                if (type != UriHostNameType.IPv4)
                {
                    Dns.GetHostAddresses(box.Text);
                }
            }
            catch (Exception)
            {
                //((TextBox)sender).Text = "Invalid host.";
            }
        }

        void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBox1.Checked)
            {
                this.btnMPDC.Enabled = false;
                this.btcSPC.Enabled = false;
                this.btnSPH.Enabled = false;
            }
            else
            {
                this.btnMPDC.Enabled = true;
                this.btcSPC.Enabled = true;
                this.btnSPH.Enabled = true;
            }
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Tabs.SelectTab(0);
        }
        private void btnMulti_Click(object sender, EventArgs e)
        {
            Tabs.SelectTab(1);
        }
        public  void btnSingle_Click(object sender, EventArgs e)
        {
            Tabs.SelectTab(2);
        }
        private void btnTools_Click(object sender, EventArgs e)
        {
            Tabs.SelectTab(3);
        }
        private void Tabs_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void btn_update_Click(object sender, EventArgs e)
        {
            StartUpdate();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            new Settings().ShowDialog();
        }

        //Functions

        private  void CheckNewVersion()
        {
            try
            {
                HttpWebResponse response2;
                List<string> list = new List<string>();
                byte[] buffer = new byte[0x2000];
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_Config.UpdateBaseUrl + "/Mw3Launcher.inf");
                HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(_Config.UpdateBaseUrl + "/Mw3Launcher.inf");
                HttpWebResponse response = TryToGetData(request);
                if (response == null)
                {
                    HttpWebResponse response3 = TryToGetData(request2);
                    if (response3 == null)
                    {
                        return;
                    }
                    response2 = response3;
                }
                else
                {
                    response2 = response;
                }
                Stream responseStream = response2.GetResponseStream();
                string item = null;
                int count = 0;
                do
                {
                    count = responseStream.Read(buffer, 0, buffer.Length);
                    if (count != 0)
                    {
                        item = Encoding.ASCII.GetString(buffer, 0, count);
                        list.Add(item);
                    }
                }
                while (count > 0);

                string ver = list[0];
                if (ver.Length > 20) ver = "{?}";//Handle errors
                string CurrentVer="";
                string Status="";
                if(File.Exists("MW3Launcher.inf"))CurrentVer=File.ReadAllText("MW3Launcher.inf");
                if (CurrentVer == "")
                {
                    if (MessageBox.Show("It seems you just installed MW3launcher.To cuntiniue you have to Update it.\nLastest version:" + ver + "\nClick yes to start update", "New version avilable", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        StartUpdate();
                    Status="Needs update";
                }
                else if (ver == CurrentVer)
                {
                    //Updated
                     Status="Updated!";
                }
                else
                {
                    
                    if (MessageBox.Show("Your client is not updated!\n" + "Your client:" + CurrentVer + "\nLastest version:" + ver + "\nClick yes to start update", "New version avilable", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        StartUpdate();
                     Status="Needs update";
                }

                this.Invoke(new MethodInvoker(delegate
                {
                    Text += " - " + Status;
                }
        ));

            }
            catch (Exception)
            {
            }
        }

        private void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[0x8000];
            while (true)
            {
                int count = input.Read(buffer, 0, buffer.Length);
                if (count <= 0)
                {
                    return;
                }
                output.Write(buffer, 0, count);
            }
        }

        private void FetchNews()
        {
            try
            {
                WebClient w = new WebClient();
                string g= w.DownloadString(_Config.NewsUrl);
                if (g.StartsWith("MSG"))
                {
                    MessageBox.Show(g.Substring(4), "Mw3Lancher/Teknogods Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                    if(g!="")
                        lblStatus.lblText = g;
                lblStatus.ClickUrl = _Config.HomePageUrl;
            }
            catch (Exception)
            {
                lblStatus.ClickUrl = _Config.HomePageUrl;
                lblStatus.lblText = "!";
            }
        }

        public string GetIp(string domain)
        {
            try
            {
                switch (Uri.CheckHostName(domain))
                {
                    case UriHostNameType.Unknown:
                    case UriHostNameType.Basic:
                        MessageBox.Show("Invalid hostname!");
                        return string.Empty;

                    case UriHostNameType.IPv4:
                        return domain;
                }
                return Dns.GetHostAddresses(domain)[0].ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("Invalid hostname!");
                return string.Empty;
            }
        }

        protected string GetMD5HashFromFile(string fileName)
        {
            FileStream inputStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            byte[] buffer = new MD5CryptoServiceProvider().ComputeHash(inputStream);
            inputStream.Close();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < buffer.Length; i++)
            {
                builder.Append(buffer[i].ToString("x2"));
            }
            return builder.ToString();
        }

        private static Process[] getProcesses(string name)
        {
            name = name.Replace(".exe", string.Empty);
            Process[] processesByName = Process.GetProcessesByName(name);
            if (processesByName.Length == 0)
            {
                return null;
            }
            return processesByName;
        }

        private bool IsAssemblySigned(string path)
        {
            int num;
            int num2;
            int num3;
            IntPtr zero = IntPtr.Zero;
            IntPtr phCertStore = IntPtr.Zero;
            IntPtr phMsg = IntPtr.Zero;
            if (!Win32Apis.CryptQueryObject(1, Marshal.StringToHGlobalUni(path), 0x3ffe, 14, 0, out num3, out num, out num2, ref phCertStore, ref phMsg, ref zero))
            {
                Console.WriteLine(new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return false;
            }
            if (num != 10)
            {
                return false;
            }
            return true;
        }

        public  void StartTheProcess(string ExecutableName, string arguements)
        {

            if (!System.IO.File.Exists(@".\devraw\video\startup.bik"))
            {
                if (!Directory.Exists(@".\devraw\video"))
                {
                    Directory.CreateDirectory(@".\devraw\video");
                }
                string path = @".\devraw\video\startup.bik";
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
                Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("TeknoMW3.tekntup.bik");
                FileStream output = System.IO.File.Open(path, FileMode.CreateNew);
                this.CopyStream(manifestResourceStream, output);
                manifestResourceStream.Dispose();
                output.Dispose();
            }
            RunProc proc2 = new RunProc
            {
                ExecutableName = ExecutableName,
                Commandargs = arguements
            };
            proc2.ShowDialog(this);

        }

        private static HttpWebResponse TryToGetData(HttpWebRequest request)
        {
            try
            {
                return (HttpWebResponse)request.GetResponse();
            }
            catch (Exception)
            {
                return null;
            }



        }

        private void btnCheatEngine_Click(object sender, EventArgs e)
        {
            if (File.Exists("mCheat.EXE"))
            {
                Process p = new Process();
                p.StartInfo.FileName = "mCheat.EXE";
                p.Start();
            }
            else
            {
                MessageBox.Show("Please download it at http://teknogods.com:8081/phpbb/viewtopic.php?f=40&t=6885");
            }
        }

        private void btn_quick_Click(object sender, EventArgs e)
        {
            btnMPLAN_Click(null, null);
        }

        public void StartUpdate()
        {
            if (_Config.Offline == "1")
            if (MessageBox.Show("Your are in offline mode.Do you want to continue?", "Offline mode", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
            {
                using (System.Diagnostics.Process p = new Process())
                {
                    p.StartInfo.FileName = _Config.HomePageUrl;
                    p.Start();
                }
                return;
            }

            if (File.Exists("MW3 Launcher Update.exe"))
            {
                Process p = new Process();
                p.StartInfo.FileName = "MW3 Launcher Update.exe";
                p.Start();
                Environment.Exit(0);
            }
            else
            {
                MessageBox.Show("MW3 Launcher Update.exe not found!\nTry to reinstall for fix it");
            }
            
        }

        private void lblStatus_Click(object sender, EventArgs e)
        {
            new Settings().ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Tabs.SelectedIndex = 0;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Tabs.SelectedIndex = 0;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Tabs.SelectedIndex = 0;
        }

        private void lblStatus_Load(object sender, EventArgs e)
        {

        }

        private void lblStatus_Click_1(object sender, EventArgs e)
        {
            new Settings().ShowDialog();
        }

     



    }
}